<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="商品分类">
        <el-select v-model="form.categoryId" placeholder="请选择" :popper-append-to-body="false">
          <el-option
            v-for="(category, id) in categorys"
            :key="id"
            :label="category.name"
            :value="id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="价格" >
        <el-input  v-model="form.price"></el-input>
      </el-form-item>
      <el-form-item label="库存" >
        <el-input type="number" v-model="form.stock"></el-input>
      </el-form-item>

      <el-form-item label="商品图片: " >
        <el-upload
          action="http://127.0.0.1:8888/upload/"
          :headers="headers"
          accept="image/png, image/jpeg"
          :limit="1"
          :on-success="handleAvatarSuccess"
          list-type="picture-card"
          :before-upload="beforeUploadPicture"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div slot="tip"  class="el-upload__tip">限制上传一张, 只能上传jpg/png文件，且不超过1M</div>
        </el-upload>
      </el-form-item>

      <el-form-item label="商品描述: ">
        <el-input type="textarea" v-model="form.detail" rows="5"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" plain @click="save">保存数据</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapState } from 'vuex'
const requsetUrl = 'goods'
export default {
  props: ['editid'],
  data () {
    return {
      form: {
        name: '',
        img: '',
        detail: '',
        price: '0.00',
        stock: '100',
        categoryId: '',
        userId: ''
      },
      rules: {
        // 验证用户名是否合法
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    const uid = window.sessionStorage.getItem('id')
    if (!uid) {
      window.alert('登录信息已过期，请重新登录')
      this.$router.push('/login')
    }
    this.form.userId = uid
    if (this.editid) {
      // 通过id 读原始数据
      this.$axios.get(`/${requsetUrl}/${this.editid}`, response => {
        this.form.name = response.data.name
        this.form.detail = response.data.detail
        this.form.price = response.data.price
        this.form.stock = response.data.stock
        this.form.img = response.data.img
        this.form.categoryId = response.data.categoryId ? String(response.data.categoryId) : ''
      })
    }
    this.$store.dispatch('getCategorys')
  },
  computed: {
    ...mapState(['categorys']),
    headers () {
      // 上传图片添加请求头header
      return {
        Authorization: window.sessionStorage.getItem('token') // 从本地获取token
      }
    }
  },
  methods: {
    // 上传图片前调用方法
    beforeUploadPicture (file) {
      if (file.size > 1 * 1024 * 1024) {
        this.$message.error('上传图片不能大于1M')
        return false
      }
    },
    save () {
      this.$refs.form.validate(valid => {
        if (!valid) return
        if (this.editid) {
          this.$axios.put(`/${requsetUrl}/${this.editid}`, response => {
            // 子组件要改变父组件的值
            this.$emit('update:show', false)
            this.$emit('getData')
          }, this.form)
        } else {
          this.$axios.post(`/${requsetUrl}`, response => {
            // 子组件要改变父组件的值
            this.$emit('update:show', false)
            this.$emit('getData')
          }, this.form)
        }
      })
    },
    handleAvatarSuccess (res, file) {
      if (res.status === 200) {
        this.form.img = res.data.image
      } else {
        this.$message.error(`图片上传失败:${res.message}`)
      }
    }
  }
}
</script>

<style scoped>
.el-select-dropdown {
  position: absolute;
  top: 38px !important;
  left: 0 !important;
}
</style>
